<?php
/**
 * Created by JetBrains PhpStorm.
 * User: P2DC
 * Date: 12/7/2556
 * Time: 15:48 น.
 * To change this template use File | Settings | File Templates.
 */

class Table extends TbAbstract
{
    const JOIN_ONE = 1;
    const JOIN_MANY = 2;

    static protected $_instanceTable = array();
    protected $_table;

    protected function __construct($table, $pk = null)
    {
        $this->_table = $table;
        if(!is_null($pk))
            $this->_pk = $pk;
    }

    static public function instanceTable($table)
    {
        if(empty(self::$_instanceTable[$table])){
            self::$_instanceTable[$table] = new Table($table);
        }
        $return = self::$_instanceTable[$table];
        /** @var $return Table */
        return $return;
    }

    public function joinTo($nodeName, $subKey, $itemKey, &$item, $mode = self::JOIN_ONE)
    {
        $inList = Helper::listArrVal($itemKey, $item);
        $sub = $this->get(array($subKey=> $inList));
        foreach($item as $key => $value){
            $item[$key][$nodeName] = $mode==self::JOIN_ONE?
                Helper::findArrOne($subKey, $value[$itemKey], $sub):
                Helper::findArr($subKey, $value[$itemKey], $sub);
        }
        return $item;
    }

    public function joinOneTo($nodeName, $subKey, $itemKey, &$item, $mode = self::JOIN_ONE)
    {
        $sub = $this->get(array($subKey=> $item[$itemKey]));
        $item[$nodeName] = $mode==self::JOIN_ONE?
            Helper::findArrOne($subKey, $item[$itemKey], $sub):
            Helper::findArr($subKey, $item[$itemKey], $sub);
        return $item;
    }
}